<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 2020-05-02
 * Time: 16:54
 */

namespace app\api\service;


use app\admin\model\Air;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopdevice;
use app\admin\model\Shopks;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproombook;
use app\admin\model\Shopstaff;
use app\admin\model\Shoptable;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userwithdraw;
use fast\Http;

class KsService
{
    protected $appKey = "ks661184720738998777";
    protected $appSecret = "Eb_O_GneEhRTgfFHSx8Bsg";
    protected $signSecret = "850bafe071fde0752d8c1411d071135a";
    protected $msgKey = "JnY3KV/fELpsGpM7VJ4G1A==";

    protected $refresh_url = "https://lbs-open.kuaishou.com/oauth2/refresh_token";



    public function prepare($redis,$param)
    {

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $param['shop_id'])->find();

        $result = array();
        $merchantId = $shop['ks_id'];
        $cache = $redis->get($merchantId);
        $shopKsModel = new Shopks();

        if($cache == ''){
            $result['code'] = 0;
            $result['msg'] = "商家未授权";
            return $result;
        }
        $cache = json_decode($cache,true);
        $access_token = $cache['access_token'];
        $expires_in = $cache['expires_in'];
        if($expires_in <strtotime("-1 minute")){
            $p = array();
            $p['ks_id'] = $merchantId;
            $access_token = $this->refresh($redis,$p);
        }

        $url = "https://lbs-open.kuaishou.com/goodlife/v1/fulfilment/certificate/prepare";

        $code = $param['code'];
        $req = array();
        if (substr($code, 0, 5) == "https") {

            $headers = get_headers($code, TRUE);
            $reqUrl = $headers['Location'];
            $data = parse_url($reqUrl);
            parse_str($data['query'], $results);
            $objData = $results['object_id'];
            $req['encrypted_data'] = $objData;
        }else{
            $req['code'] = $code;
        }

        error_log("===req==".json_encode($req));

        $res =  KsService::get2($url,$req,$access_token);

        error_log("====ks res==".json_encode($res));
        $error_code = $res['data']['error_code'];
        $description = $res['data']['description'];
        if($error_code == 0){

            $result['code'] = 1;
            $result['msg'] = "";
            $result['verify_token'] = $res['data']['verify_token'];
            $certificates =  $res['data']['certificates'];
            $result['ks_order_id'] = $res['data']['order_id'];
            if(count($certificates) == 0){
                $result['code'] = 0;
                $result['msg'] = "暂无可用券产品";
            }else{
                $result['sku_id'] =$certificates[0]['sku']['sku_id'];
                $result['encrypted_code'] = $certificates[0]['encrypted_code'];

            }
        }else{
            $result['code'] = 0;
            $result['msg'] = $description;
        }
        return $result;
    }


    public function verify($redis,$param)
    {

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $param['shop_id'])->find();

        $result = array();
        $merchantId = $shop['ks_id'];
        $cache = $redis->get($merchantId);
        if($cache == ''){
            $result['code'] = 0;
            $result['msg'] = "商家未授权";
            return $result;
        }
        $cache = json_decode($cache,true);
        $access_token = $cache['access_token'];
        $expires_in = $cache['expires_in'];
        if($expires_in <strtotime("-1 minute")){
            $p = array();
            $p['ks_id'] = $merchantId;
            $access_token = $this->refresh($redis,$p);
        }

        $url = "https://lbs-open.kuaishou.com/goodlife/v1/fulfilment/certificate/verify";
        $req = array();
        $req['verify_token'] = $param['verify_token'];
        $req['poi_id'] = $merchantId;
        $req['order_id'] = $param['order_no'];
        $codes = array();
        $codes[] = $param['encrypted_code'];
        $req['encrypted_codes'] = $codes;

        error_log("==ksVerfiy==".json_encode($req));
        $res =  KsService::post($url,json_encode($req),$access_token);
        $res = json_decode($res,true);
        $error_code = $res['data']['error_code'];
        $description = $res['data']['description'];
        if($error_code == 0){

            $verifyResult = $res['data']['verify_results'][0];
            $result['code'] = 1;
            $result['msg'] = "";
            $result['origin_code'] = $verifyResult['origin_code'];
            $result['pay_amount'] = $verifyResult['verify_amount_info']['pay_amount'];
        }else{
            $result['code'] = 0;
            $result['msg'] = $description;
        }
        return $result;
    }





    public function refresh($redis,$param)
    {

        $shopModel = new Shop();
        $shop = $shopModel->where('ks_id',$param['ks_id'])->find();

        $req = array();
        $req['app_id'] = $this->appKey;
        $req['grant_type'] = "refresh_token";
        $req['refresh_token'] = $shop['ks_refresh_token'];
        $req['app_secret'] = $this->appSecret;

        $result = Http::get($this->refresh_url,$req);
        $result = json_decode($result,true);
        $code = $result['result'];
        if($code == 1){

            $access_token = $result['access_token'];
            $refresh_token = $result['refresh_token'];


            $cache = array();
            $cache['access_token'] = $access_token;
            $cache['expires_in'] = strtotime("+48 hour");

            $redis->set($param['ks_id'],json_encode($cache));
            if($shop){
                $shopModel->where('id',$shop['id'])->update(['ks_refresh_token'=>$refresh_token]);
            }
            return $access_token;
        }else{
            error_log("======快手授权刷新token======".json_encode($result));
            return "";
        }

    }

    public static function get($url, $params = [], $headers = [])
    {
        $ch = curl_init();
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        $output = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            Log::error('HTTP GET Request Error: ' . $error);
            throw new HttpException(500, 'HTTP GET Request Error: ' . $error);
        }

        return json_decode($output, true);
    }


    public static function get2($url, $params = [], $token)
    {
        $ch = curl_init();
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'access-token: '.$token
            )
        );

        $output = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            Log::error('HTTP GET Request Error: ' . $error);
            throw new HttpException(500, 'HTTP GET Request Error: ' . $error);
        }

        return json_decode($output, true);
    }

    public static  function post($url, $jsonStr,$token)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr),
                'access-token: '.$token
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);


        return $response;
    }



}